package com.wfcm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.wfcm.annotation.IgnoreSign;
import com.wfcm.annotation.IgnoreToken;
import com.wfcm.entity.WfQrcodeEntity;
import com.wfcm.entity.WfWxMenuEntity;
import com.wfcm.entity.WfWxShareEntity;
import com.wfcm.entity.WxMessage;
import com.wfcm.service.*;
import com.wfcm.utils.*;
import com.wfcm.wxPay.WXPayUtil;
import com.wfcm.wxPay.WXUtil;
import com.wfcm.wxUitls.TextMessage;
import com.wfcm.wxUitls.WxPushText;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.net.URLEncoder;

@Controller
@RequestMapping("/wxMessage")
@ResponseBody
public class WxMessageController {

	private static  Logger log = LoggerFactory.getLogger(WxMessageController.class);
	 @Autowired
	 private WfMemberService memberService;
	 @Autowired
	 private WfMemberSessionService memberSessionService;
	 @Autowired
	 private WfWxShareService wxShareService;
    @Autowired
    private WfQrcodeService qrcodeService;
    @Autowired
    private WfWxMenuService wxMenuService;

    @RequestMapping("/test")
    @IgnoreToken
    @IgnoreSign
    public void test(){
        String scene ="";
        String content1 = qrcodeService.queryContent(scene).getContent();
        System.out.println("content1:"+content1);

        String EventKey ="V1001_TEACHER_PHONE";
        String content2 = wxMenuService.queryContent(EventKey).getContent();
        System.out.println("****content2:"+content2);

        String str = WxPushText.getInfo();
        System.out.println("****str:"+str);
    }

    @RequestMapping("/save")
    @IgnoreToken
    @IgnoreSign
    public void save(String content){

        String EventKey ="V1001_TEACHER_PHONE";
        WfWxMenuEntity content2 = wxMenuService.queryContent(EventKey);
        content2.setContent(content);
        wxMenuService.update(content2);
        System.out.println("****content2:"+content2);

    }


    /**
     * 微信消息接收和token验证
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/handlePublicMsg")
    @IgnoreToken
    @IgnoreSign
    public void hello(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        PrintWriter print;
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && WXUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 处理微信公众号请求信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/hello")
    @IgnoreToken
    @IgnoreSign
    public String handlePublicMsg(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce"); // 随机数

        //token验证
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        PrintWriter print = null;
        if (isGet) {
            String signature = request.getParameter("signature");// 微信加密签名
            String echostr = request.getParameter("echostr");// 随机字符串
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && WXUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if(null != print){
                        print.close();
                    }
                }
            }else{
                log.debug("微信token验证失败");
                return null;
            }
        }
        WxMessage decrypt = new WxMessage();
        decrypt.setTimestamp(timestamp);
        decrypt.setNonce(nonce);
        String encrypt_type =request.getParameter("encrypt_type");
        decrypt.setEncrypt_type(encrypt_type);

        if (encrypt_type == null || encrypt_type.equals("raw")) { //不用加密
            String signature = request.getParameter("signature");
            log.debug("*****微信签名signature:"+signature);
            System.out.println("*****signature:"+signature);
            decrypt.setSignature(signature);
        }else {//需走加解密流程
            // 微信加密签名
            String msgSignature = request.getParameter("msg_signature");
            System.out.println("*****msg_signature:"+msgSignature);
            decrypt.setMsg_signature(msgSignature);

            //密文  获取微信端返回数据
            /*String encryptMsg = streamToString(request);*/
           //String data = WXUtil.decryptMsg(msgSignature, timeStamp, nonce, encryptMsg);
        }
        // 获得微信端返回的xml数据
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            is = request.getInputStream();
            isr = new InputStreamReader(is, "utf-8");
            br = new BufferedReader(isr);
            String str = null;
            StringBuffer returnXml= new StringBuffer();
            while ((str = br.readLine()) != null) {
                //返回的是xml数据
                returnXml.append(str);
            }
            /*Map<String, String> encryptMap = WXPayUtil.xmlToMap(returnXml.toString());*/
            // 得到公众号传来的加密信息并解密,得到的是明文xml数据
            //String decryptXml = WXPublicUtils.decrypt(encryptMap.get("Encrypt"));
            log.debug("*****debug : returnXml查看返回数据："+returnXml);
            System.out.println("*****returnXml查看返回数据："+returnXml);
            // 将xml数据转换为map
            //Map<String, String> decryptMap = xmlToMap(request,decrypt);
            str = returnXml.toString();
            Map<String, String> decryptMap = XMLUtil.doXMLParse(str);
            // 区分消息类型
            String msgType = decryptMap.get("MsgType");

            String encryptMsg = "";
            // 普通消息
            if ("text".equals(msgType)) { // 文本消息
                // todo 处理文本消息
                String Content = decryptMap.get("Content");//事件KEY值，qrscene_为前缀，后面为二维码的参数值
                // 返回消息时ToUserName的值与FromUserName的互换
                TextMessage message = null;
                if("入群".equals(Content)){//根据场景值判断返回内容
                    message =  new TextMessage(decryptMap.get("FromUserName"), decryptMap.get("ToUserName"), new Date().getTime() + "", "text",  WxPushText.getInto());
                }else if("咨询".equals(Content)){//默认返回内容
                    message =  new TextMessage(decryptMap.get("FromUserName"), decryptMap.get("ToUserName"), new Date().getTime() + "", "text",  WxPushText.getTel());
                }else {//默认返回内容
                    message =  new TextMessage(decryptMap.get("FromUserName"), decryptMap.get("ToUserName"), new Date().getTime() + "", "text",  WxPushText.getReply());
                }
                //可以根据tiket来获取对应的sence值
                System.out.println("*****TextMessage:"+message.toString());
                encryptMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + WxMessageUtil.getInstance().textMessageToXml(message);
                System.out.println("encryptMsg:"+encryptMsg);
            } else if ("image".equals(msgType)) { // 图片消息
                // todo 处理图片消息
            } else if ("voice".equals(msgType)) { //语音消息
                // todo 处理语音消息
            } else if ("video".equals(msgType)) { // 视频消息
                // todo 处理视频消息
            } else if ("shortvideo".equals(msgType)) { // 小视频消息
                // todo 处理小视频消息
            } else if ("location".equals(msgType)) { // 地理位置消息
                // todo 处理地理位置消息
            } else if ("link".equals(msgType)) { // 链接消息
                // todo 处理链接消息
            }
            // 事件推送
            else if ("event".equals(msgType)) { // 事件消息
                // 区分事件推送
                String event = decryptMap.get("Event");
                if ("subscribe".equals(event)) { // 订阅事件时Eventkey为空 或 未关注扫描二维码事件
                    String EventKey = decryptMap.get("EventKey");//事件KEY值，qrscene_为前缀，后面为二维码的参数值
                    String scene = "";
                    if(EventKey.length()!=0){
                        scene = EventKey.substring(8);
                        System.out.println("*****二维码对应scene值--EventKey:"+EventKey);
                    }
                    TextMessage message = null;
                    if("123".equals(scene)){//根据场景值判断返回内容
                        message =  new TextMessage(decryptMap.get("FromUserName"), decryptMap.get("ToUserName"), new Date().getTime() + "", "text",  WxPushText.get123());
                    }else if("124".equals(scene)){//根据场景值判断返回内容
                        message =  new TextMessage(decryptMap.get("FromUserName"), decryptMap.get("ToUserName"), new Date().getTime() + "", "text",  WxPushText.get124());
                    }else{//默认返回内容
                        message =  new TextMessage(decryptMap.get("FromUserName"), decryptMap.get("ToUserName"), new Date().getTime() + "", "text",  WxPushText.getInfo());
                    }
                    System.out.println("*****TextMessage:"+message.toString());
                    encryptMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + WxMessageUtil.getInstance().textMessageToXml(message);
                    System.out.println("encryptMsg:"+encryptMsg);
                }  else if ("unsubscribe".equals(event)) { // 取消订阅事件
                    // todo 处理取消订阅事件
                } else if ("SCAN".equals(event)) { // 已关注扫描二维码事件
                    String EventKey = decryptMap.get("EventKey");//事件KEY值，qrscene_为前缀，后面为二维码的参数值
                   /* String scene = "";
                    if(EventKey.length()!=0){
                        scene = EventKey.substring(8);
                        System.out.println("*****二维码对应scene值--EventKey:"+EventKey);
                    }*/
                    System.out.println("*****二维码对应scene值--EventKey:"+EventKey);
                    TextMessage message = null;
                    if("123".equals(EventKey)){//根据场景值判断返回内容
                        message =  new TextMessage(decryptMap.get("FromUserName"), decryptMap.get("ToUserName"), new Date().getTime() + "", "text",  WxPushText.get123());
                    }else if("124".equals(EventKey)){//根据场景值判断返回内容
                        message =  new TextMessage(decryptMap.get("FromUserName"), decryptMap.get("ToUserName"), new Date().getTime() + "", "text",  WxPushText.get124());
                    }else {//默认返回内容
                        // 返回消息时ToUserName的值与FromUserName的互换
                        message = new TextMessage(decryptMap.get("FromUserName"), decryptMap.get("ToUserName"), new Date().getTime() + "", "text", WxPushText.getYGZ());
                    }
                    System.out.println("*****TextMessage:"+message.toString());
                    encryptMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + WxMessageUtil.getInstance().textMessageToXml(message);
                    System.out.println("encryptMsg:"+encryptMsg);
                } else if ("LOCATION".equals(event)) { // 上报地理位置事件
                    // todo 处理上报地理位置事件
                } else if ("CLICK".equals(event)) { // 点击菜单拉取消息时的事件推送事件
                    String EventKey = decryptMap.get("EventKey");//获取对应的推送时间key
                    if("V1001_TEACHER_PHONE".equals(EventKey)) {//V1001_TEACHER_PHONE 点击获取老师联系方式
                        //TextMessage message = new TextMessage(decryptMap.get("FromUserName"), decryptMap.get("ToUserName"), new Date().getTime() + "", "text", wxMenuService.queryContent(EventKey).getContent());
                        TextMessage message = new TextMessage(decryptMap.get("FromUserName"), decryptMap.get("ToUserName"), new Date().getTime() + "", "text", WxPushText.getTel());
                        System.out.println("*****TextMessage:"+message.toString());
                        encryptMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + WxMessageUtil.getInstance().textMessageToXml(message);
                    }
                    System.out.println("encryptMsg:"+encryptMsg);
                    // todo 处理点击菜单拉取消息时的事件推送事件
                } else if ("VIEW".equals(event)) { // 点击菜单跳转链接时的事件推送
                    // todo 处理点击菜单跳转链接时的事件推送
                }
            }
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(encryptMsg);
            response.getWriter().close();
            /*return encryptMsg;*/
        } catch (Exception e) {
            log.error("处理微信公众号请求信息，失败", e);
        } finally {
            if(null != print){
                print.close();
            }
            if (null != is) {
                is.close();
            }
            if (null != isr) {
                isr.close();
            }
            if (null != br) {
                br.close();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        TextMessage message = new TextMessage("FromUserName", "ToUserName", new Date().getTime() + "", "text", "啦啦啦啦啦啦的九分裤绝地反击");
        System.out.println("*****TextMessage:"+message.toString());
        String m = messageToXml(message);
        System.out.println("******m:"+m);
    }

    /**
     * 文本消息对象转换成xml
     *
     * @param textMessage 文本消息对象
     * @return xml
     */
    public static String messageToXml(TextMessage textMessage) {
        xstream.alias("xml", textMessage.getClass());
        return xstream.toXML(textMessage);
    }

    /**
     * 扩展xstream使其支持CDATA
     */
    private static XStream xstream = new XStream(new XppDriver() {
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                // 对所有xml节点的转换都增加CDATA标记
                boolean cdata = true;
                @SuppressWarnings("unchecked")
                public void startNode(String name, Class clazz) {
                    super.startNode(name, clazz);
                }
                protected void writeText(QuickWriter writer, String text) {
                    /*if (cdata) {
                        writer.write("");
                    } else {*/
                        writer.write(text);
                    //}
                }
            };
        }
    });


    /**
     * 获取微信公众号二维码
     * @param codeType 二维码类型 "1": 临时二维码  "2": 永久二维码
     * @param sceneId 场景值ID sceneId 即为我们可以携带的参数
     *                临时二维码时为32位非0整型，永久二维码时最大值为100000（目前参数只支持1–100000）
     */
    @RequestMapping(value = "/getWXPublicQRCode",method = RequestMethod.POST)
    @ResponseBody
    @IgnoreToken
    @IgnoreSign
    public R getWXPublicQRCode(String codeType,Integer expireseconds, Integer sceneId,String content) {

        WfWxShareEntity accessToken  = wxShareService.queryObject(1);
        JSONObject jsonObj= FastJSONUtils.getJSONObject(accessToken.getContent());
        String wxAccessToken = jsonObj.getString("access_token");
        System.out.println("wxAccessToken:"+wxAccessToken);
        Map<String, Object> map = new HashMap<>();
        if ("1".equals(codeType)) { // 临时二维码
            map.put("expire_seconds", 604800);
            map.put("action_name", "QR_SCENE");
            Map<String, Object> sceneMap = new HashMap<>();
            Map<String, Object> sceneIdMap = new HashMap<>();
            sceneIdMap.put("scene_id", sceneId);
            sceneMap.put("scene", sceneIdMap);
            map.put("action_info", sceneMap);
        } else if ("2".equals(codeType)) { // 永久二维码
            map.put("action_name", "QR_LIMIT_SCENE");
            Map<String, Object> sceneMap = new HashMap<>();
            Map<String, Object> sceneIdMap = new HashMap<>();
            sceneIdMap.put("scene_id", sceneId);
            sceneMap.put("scene", sceneIdMap);
            map.put("action_info", sceneMap);
        }
        String data = JSON.toJSONString(map);
        System.out.println("data:"+data);
        // 得到ticket票据,用于换取二维码图片
        JSONObject jsonObject = HttpUtil.httpsRequest("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + wxAccessToken, "POST", data);
        System.out.println("jsonObject:"+jsonObject);
        String ticket = (String) jsonObject.get("ticket");
        // WXConstants.QRCODE_SAVE_URL: 填写存放图片的路径
        String newUrl = httpsRequestPicture("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + URLEncoder.encode(ticket),
                "GET", null);
        qrcodeService.save(new WfQrcodeEntity(ticket,"http://wangfang.oss-cn-qingdao.aliyuncs.com/"+newUrl,Integer.valueOf(codeType),sceneId,expireseconds,new Date(),content));
        return R.ok();
    }



    /**
     * 发送https请求，返回二维码图片
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param data 提交的数据
     */
    public static String httpsRequestPicture(String requestUrl, String requestMethod, String data) {
        InputStream inputStream = null;
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //conn.setUseCaches(false);
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(15000);
            //设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.connect();
            //当data不为null时向输出流写数据
            /*if (null != data) {
                //getOutputStream方法隐藏了connect()方法
                OutputStream outputStream = conn.getOutputStream();
                //注意编码格式
                outputStream.write(data.getBytes("UTF-8"));
                outputStream.close();
            }*/
            // 从输入流读取返回内容
            /*inputStream = conn.getInputStream();*/
            log.info("开始生成微信二维码...");
            String newsUrl = OSSUtil.putFile(conn, "qrcode", Constants.IGM_BUCKET);
            /*inputStreamToMedia(inputStream,  "C:/Users/Administrator/Pictures", "test123", "jpg");*/
            log.info("微信二维码生成成功!!!");
            conn.disconnect();
            return newsUrl;
        } catch (Exception e) {
            log.error("发送https请求失败，失败", e);
        }finally {
            //释放资源
            try {
                if(null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error("释放资源失败，失败", e);
            }
        }
        return null;
    }


    //上传图片素材/上传图文消息内的图片获取URL
    // url - 路径
    //filePath 图片绝对路径
    private String postFile(String url, String filePath) {
        File file = new File(filePath);
        if (!file.exists())
            return null;
        String result = "";
        try {
            URL url1 = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            String boundary = "-----------------------------" + System.currentTimeMillis();
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            OutputStream output = conn.getOutputStream();
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write(
                    String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName())
                            .getBytes());
            output.write("Content-Type: image/jpeg \r\n\r\n".getBytes());
            byte[] data = new byte[1024];
            int len = 0;
            FileInputStream input = new FileInputStream(file);
            while ((len = input.read(data)) > -1) {
                output.write(data, 0, len);
            }
            output.write(("\r\n--" + boundary + "\r\n\r\n").getBytes());
            output.flush();
            output.close();
            input.close();
            InputStream resp = conn.getInputStream();
            StringBuffer sb = new StringBuffer();
            while ((len = resp.read(data)) > -1)
                sb.append(new String(data, 0, len, "utf-8"));
            resp.close();
            result = sb.toString();
        } catch (IOException e) {
            log.error("postFile数据传输失败", e);
        }
        return result;
    }

    /**
     * 将输入流转换为图片
     * @param input 输入流
     * @param savePath 图片需要保存的路径
     * @param fileType 图片类型
     */
    public static void inputStreamToMedia(InputStream input, String savePath, String fileName, String fileType) throws Exception {
        String filePath = savePath + "/" + fileName + "." + fileType;
        File file = new File(filePath);
        FileOutputStream outputStream = new FileOutputStream(file);
        int length;
        byte[] data = new byte[1024];
        while ((length = input.read(data)) != -1) {
            outputStream.write(data, 0, length);
        }
        outputStream.flush();
        outputStream.close();
    }


    public static String streamToString(HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * msg解密后xml转为map集合
     *
     * @param request
     * @param msg
     * @return
     * @throws IOException
     */
    public static Map<String, String> xmlToMap(HttpServletRequest request, WxMessage msg) throws Exception {
        SAXReader reader = new SAXReader();
        String token = "haofangfa2018";
        String encodingAesKey = "pCjA6oqdwOR5jqtw8O8jK0xamyv2VfxLQ7yDB6xKIPp";
        String appId = ConstantUtil.GG_APP_ID;
        //获取加密消息xml字符串
      /*  String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
        Document document = reader.read(request.getInputStream());
        Element rootElement = document.getRootElement();
        Element encrypt = rootElement.element("Encrypt");*/
//        String fromXML = String.format(format, encrypt.getText());


        String fromXML = streamToString(request);
       /* //解密消息
        WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
        //获得解密消息
        String result = pc.decryptMsg(msg.getMsg_signature(), msg.getTimestamp(), msg.getNonce(), fromXML);*/
        Map<String, String> map = new HashMap<>(6);
        //将解密后的消息转为xml
        Document doc = DocumentHelper.parseText(fromXML);
        Element root = doc.getRootElement();
        List<Element> list = root.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        return map;
    }

    /**
     * URL编码（utf-8）
     *
     * @param source
     * @return
     */
    public static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


    /**
     * 处理微信公众号请求信息
     * @param request
     * @return
     */
   /* @RequestMapping("/wxpublic/verify_wx_token")
    @ResponseBody
    public String handlePublicMsg1(HttpServletRequest request) throws Exception {

        //request 为请求的 HttpServletRequest 参数
        String encrypt_type =request.getParameter("encrypt_type");
        if (encrypt_type == null || encrypt_type.equals("raw")) { //不用加密
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");

            if(WXUtil.checkSignature(signature, timestamp, nonce)) {
                //业务处理方法，返回为XML格式的结果信息 此处需要转换一下编码,否则中文乱码，不知为何...
                String respMessage = new String(wxService.processRequest(request.getInputStream(),session).getBytes("UTF-8"),"ISO8859_1");
                log.info("message:"+respMessage);
                return respMessage;
            } else {
                return "check Error";
            }
        } else {//需走加解密流程
            // 微信加密签名
            String msgSignature = request.getParameter("msg_signature");
            // 时间戳
            String timeStamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            //密文  获取微信端返回数据
            String encryptMsg = streamToString(request);

            String data = WXUtil.decryptMsg(msgSignature, timeStamp, nonce, encryptMsg);
            log.info("parse Data is:"+data);
            if(data.length() == 0) {
                return "CheckError";
            } else {
                InputStream istream = new ByteArrayInputStream(data.getBytes());
                //业务处理方法，返回为XML格式的结果信息
                String respMessage = wxService.processRequest(istream,session);
                log.info("message:"+respMessage);
                String enRespMsg = WXUtil.ecryptMsg(respMessage, timeStamp, nonce);
                return enRespMsg;
            }
        }

    }*/


}
